import { useState } from 'preact/hooks'; // 引入 useState
import { ChatTopic } from '../../entity';
import { Namespace } from '../../utils';
import { LinkSvg, MoreSvg } from '../../icons'; // 引入 SVG 图标
import { Popup } from '../popup/popup';
import './chat-topic-item.scss';

export interface ChatTopicItemProps {
  current: boolean;
  active: boolean;
  topic: ChatTopic;
  onClick: () => void;
  onAction: (action: string, event: MouseEvent) => void;
}

const ns = new Namespace('chat-topic-item');

export const ChatTopicItem = (props: ChatTopicItemProps) => {
  const { current, active, topic, onClick, onAction } = props;
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  /**
   * 跳转主数据
   *
   * @author tony001
   * @date 2025-02-24 10:02:42
   * @param {MouseEvent} event
   */
  const handleJumpToView = (event: MouseEvent) => {
    event.stopPropagation();
    onAction('LINK', event);
  };

  /**
   * 处理话题行为
   *
   * @author tony001
   * @date 2025-02-24 10:02:57
   * @param {string} actionId
   * @param {MouseEvent} event
   */
  const handleAction = (actionId: string, event: MouseEvent) => {
    if (actionId === 'DELETE') {
      onAction('DELETE', event);
    }
    setIsPopupOpen(false);
  };

  return (
    <div
      className={`${ns.b()} ${ns.is('active', active)}`}
      onClick={onClick.bind(this)}
    >
      <div className={ns.b('caption')}>{topic.caption}</div>
      <div className={ns.b('icon')}>
        <span
          className={ns.be('icon', 'item')}
          title={'跳转主视图'}
          onClick={handleJumpToView.bind(this)}
        >
          <LinkSvg className={ns.b('link-icon')} />
        </span>
        {!current ? (
          <Popup
            actions={[{ id: 'DELETE', caption: '删除话题' }]}
            position='bottom'
            isOpen={isPopupOpen}
            onToggleOpen={setIsPopupOpen}
            onAction={handleAction.bind(this)}
          >
            <span className={ns.be('icon', 'item')} title={'更多'}>
              <MoreSvg className={ns.b('more-icon')} />
            </span>
          </Popup>
        ) : null}
      </div>
    </div>
  );
};
